package cn.lyjuan.archetypes.bms.web.controller;

import cn.lyjuan.archetypes.bms.web.bean.vo.BaseResp;
import cn.lyjuan.archetypes.bms.web.config.LoginCodeFilter;
import cn.lyjuan.archetypes.bms.web.config.SecurityConfig;
import cn.lyjuan.archetypes.bms.web.controller.base.SecurityController;
import cn.lyjuan.archetypes.bms.web.cst.SessionConst;
import cn.lyjuan.archetypes.bms.web.exception.AppCode;
import cn.lyjuan.archetypes.bms.web.taglib.BmsSuffixTag;
import cn.lyjuan.archetypes.bms.web.util.AppUtils;
import cn.lyjuan.archetypes.bms.web.util.VerifyCodeUtils;
import cn.lyjuan.archetypes.bms.web.util.SessionUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

/*
 * 总入口
 */
@Controller
public class LoginController extends SecurityController
{
    private static Logger log = LogManager.getLogger(LoginController.class);

    /**
     * 在 session 超时后，如果请求了一个ajax，SpringSecurity会将该
     * ajax转发为 tologin 的ajax，所以这里在需要处理 ajax 的请求，
     * 并在 JS 的 ajax 响应里回应需要登录的信息，跳转或打开登录窗口。
     *
     * @return
     */
    @RequestMapping(SecurityConfig.LOGIN_PAGE)
    public ModelAndView tologin()
    {
        if (AppUtils.isAjax())
        {
            AppUtils.respJson(BaseResp.resp(AppCode.NO_LOGIN));
            return null;
        }

        if (null != param("dialog"))
            // todo login dialog
            return new ModelAndView("/loginDialog");

        return new ModelAndView("/login");
    }

    @RequestMapping(SecurityConfig.LOGIN_SUCC)
    public ModelAndView succ() throws IOException
    {
        if (AppUtils.isAjax())
        {
            AppUtils.respJson(BaseResp.resp());
            return null;
        }

        String index = BmsSuffixTag.suffix(SecurityConfig.INDEX);

        return new ModelAndView("redirect:" + index);
    }

    @RequestMapping(SecurityConfig.LOGIN_FAIL)
    public ModelAndView fail() throws IOException
    {
        String appMsg = "Unknown Error";

        AuthenticationException err = SessionUtils.get(WebAttributes.AUTHENTICATION_EXCEPTION,
                AuthenticationException.class);

        Exception e = SessionUtils.get(WebAttributes.AUTHENTICATION_EXCEPTION, Exception.class);
        log.error("login err：", e);

        if (null != err)
        {
            appMsg = err.getMessage();

            if ("Bad credentials".equalsIgnoreCase(appMsg))
                appMsg = "用户名或密码错误";
            else if (LoginCodeFilter.LOGIN_CODE_ERROR.equalsIgnoreCase(appMsg))
                appMsg = "验证码错误";
        }

        if (AppUtils.isAjax())
        {
            AppUtils.respJson(BaseResp.resp(AppCode.ERR, appMsg));
            return null;
        }

        ModelAndView mav = new ModelAndView("/login");
        mav.addObject("result", appMsg);

        return mav;
    }

    /**
     * 验证码
     */
    @RequestMapping(SecurityConfig.LOGIN_CODE)
    public void code()
    {
        //生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);

        SessionUtils.set(SessionConst.LOGIN_CODE, verifyCode.toLowerCase());

        //生成图片
        int w = 250, h = 100;
        VerifyCodeUtils.outputImage(w, h, out(), verifyCode);
    }
}
